import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import '../src/assets/iconfont.js';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import router from './router';
import dayjs from 'dayjs';
import i18n from './i18n/index';
// // 导入修正路径后的语言配置
import { langConfig } from './i18n/ElementPlus_Language_config';
// 导入所需的dayjs本地化（按需添加）
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';
import 'dayjs/locale/ja';
import 'dayjs/locale/ko';
import 'dayjs/locale/fr';

const app = createApp(App);

// 注册Element图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

// 修复：正确获取i18n当前语言（兼容响应式和非响应式情况）
const getCurrentLang = () => {
  // 检查是否为响应式对象（有value属性）
  const locale = i18n.global.locale;
  return typeof locale === 'object' && 'value' in locale ? locale.value : locale;
};

// 初始化配置
const initLang = getCurrentLang();
// 带类型断言避免TS7053错误
const defaultConfig = langConfig[initLang as keyof typeof langConfig] || langConfig['zh-CN'];

// 初始化Element Plus
app.use(ElementPlus, {
  locale: defaultConfig.elementLocale,
  dayjsLocale: defaultConfig.dayjsLocale,
});

const locale = i18n.global.locale;
// 明确类型断言，告诉TS locale是具有subscribe方法的响应式对象
if (typeof locale === 'object' && 'subscribe' in locale) {
  (locale.subscribe as (callback: (value: string) => void) => void)((newLang: string) => {
    const config = langConfig[newLang as keyof typeof langConfig] || langConfig['zh-CN'];
    // 同步Element Plus配置
    app.config.globalProperties.$ELEMENT.locale = config.elementLocale;
    app.config.globalProperties.$ELEMENT.dayjsLocale = config.dayjsLocale;
    // 同步day.js
    dayjs.locale(config.dayjsLocale);
  });
}
// 挂载插件
app.use(router);
app.use(store);
app.use(i18n);
app.mount('#app');